package com.iefgames.cs.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.iefgames.cs.framework.support.MD5;
import com.iefgames.cs.manager.CsManager;
import com.iefgames.cs.pople.Cs;

public class Login extends HttpServlet {
	
	private static Log logger = LogFactory.getLog(Message.class); 
	
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Enumeration<String> names = request.getParameterNames();
		
		String name = null;
		ArrayList<String> params = new ArrayList<String>();
		while (names.hasMoreElements()) {
			params.add((name = names.nextElement()) + "=" + request.getParameter(name));
		}
		
		logger.info(request.getRequestURI() + params.toString());
		
		String username = null, password = null;
		try {
			username = request.getParameter("username").trim();
			password = request.getParameter("password").trim();
		} catch (NullPointerException ne) {
			logger.warn(ne);
			return;
		}
		
		String sessionId = null;
		
		PrintWriter writer = null;
		try {
			response.setContentType("text/html; charset=utf-8");
			writer = response.getWriter();
			writer.append("<script type='text/javascript'>");
			writer.append("window.location='http://im.cs.iefgames.com/?");
//			writer.append(sessionId = MD5.MD5Encode(username));		//for test，下面（67行）也需要修改
			writer.append(sessionId = MD5.MD5Encode(username + password + new Date().getTime()));
			writer.append("';</script>");
			writer.flush();
		} catch (IOException ioe) {
			return;
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
		
		Cs cs = new Cs();
		cs.setUuid(MD5.MD5Encode(username));
		cs.setSessionId(sessionId);
		
		CsManager.add(cs.getUuid(), cs);
	}
//	
//	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		doPost(request, response);
//	}
}
